package com.wis.activity;

import android.app.ActionBar;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

//import com.umeng.analytics.MobclickAgent;
import com.wis.BuildConfig;
import com.wis.R;
import com.wis.application.WisApplication;
import com.wis.bean.Person;
import com.wis.db.DBManager;
import com.wis.util.ImageUtils;
import com.wis.face.WisUtil;
import com.wis.util.SingleMediaScanner;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;


import face.entity.FaceModel;

public class AddActivity extends Activity implements View.OnClickListener {

    private WisApplication application;

    private Button leftLocalBtn, leftTakeBtn, addBtn;
    private ImageView leftImageView;
    private EditText nameView;
    private ActionBar actionBar;

    private static final int PHOTO_REQUEST_TAKEPHOTO = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 结果

    private Bitmap photo;
    private File tempFile = new File(Environment.getExternalStorageDirectory(), "temp.jpg");

    private DBManager dbManager;

    private Uri uritempFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);
        application = (WisApplication) getApplication();
        actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        initView();
        //初始化DBManager
        dbManager = new DBManager(this);
    }

    private void initView() {
        leftImageView = (ImageView) findViewById(R.id.left_img);

        leftLocalBtn = (Button) findViewById(R.id.left_local);
        leftTakeBtn = (Button) findViewById(R.id.left_take);
        leftLocalBtn.setOnClickListener(this);
        leftTakeBtn.setOnClickListener(this);

        nameView = (EditText) findViewById(R.id.name);

        addBtn = (Button) findViewById(R.id.add);
        addBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.left_local:
                // 本地图片
                Intent leftLocalIntent = new Intent(Intent.ACTION_PICK, null);
                leftLocalIntent.setDataAndType(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(leftLocalIntent, PHOTO_REQUEST_GALLERY);
                break;
            case R.id.left_take:
                if (tempFile == null) {
                    new File(Environment.getExternalStorageDirectory(), "temp.jpg");
                }
                if (!tempFile.getParentFile().exists()) {
                    tempFile.getParentFile().mkdirs();
                }
                // 调用系统的拍照功能
                Intent leftTakeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                // 指定调用相机拍照后照片的储存路径
//                leftTakeIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(tempFile));
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    if (leftTakeIntent.resolveActivity(getPackageManager()) != null) {
                        Uri photoURI = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".fileprovider", tempFile);
                        leftTakeIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                        startActivityForResult(leftTakeIntent, PHOTO_REQUEST_TAKEPHOTO);
                    }
                } else {
                    leftTakeIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
                    startActivityForResult(leftTakeIntent, PHOTO_REQUEST_TAKEPHOTO);
                }


//                leftTakeIntent.putExtra(MediaStore.EXTRA_OUTPUT,getUriForFile(AddActivity.this, tempFile));
//                startActivityForResult(leftTakeIntent, PHOTO_REQUEST_TAKEPHOTO);
                break;
            case R.id.add:
                // 保存图片到SD卡
                String name = nameView.getText().toString().trim();
                if (TextUtils.isEmpty(name)) {
                    Toast.makeText(AddActivity.this, "姓名为空", Toast.LENGTH_SHORT).show();
                    break;
                }
                if (photo == null) {
                    Toast.makeText(AddActivity.this, "图片为空", Toast.LENGTH_SHORT).show();
                    break;
                }
                saveBitmap(photo, name);

                // 检测人脸
                FaceModel faceModel[] = application.detectFaces(photo);
                if (faceModel == null) {
                    Toast.makeText(AddActivity.this, "无法检测到人脸", Toast.LENGTH_SHORT).show();
                    break;
                }

                int faceCount = faceModel.length;
                //本例子中只添加第一个人脸，如需添加人脸for(int i=0;i<faceCount;i++)
                Log.i("wisMobile", "detectFace size=" + faceCount + ",rect(x,y,width,height) = " + faceModel[0].rtFace.x + "," + faceModel[0].rtFace.y
                        + "," + faceModel[0].rtFace.width + "," + faceModel[0].rtFace.height);

                //提取第一个人脸的特征值
                float[] fea = application.extractFeature(photo,faceModel[0]);
                if (fea!=null)
                {
                    Log.i("wisMobile", "extractFeature " + fea);

                    //特征数组转化为String
                    String feaStr = "";
                    for (int i = 0; i < fea.length; i++) {
                        if (i == fea.length - 1) {
                            feaStr = feaStr + fea[i];
                        } else {
                            feaStr = feaStr + fea[i] + ",";
                        }
                    }

                    // 添加到数据库，并返回人脸管理列表
                    Person person = new Person();
                    person.name = name;
                    person.image = ImageUtils.BitmapToBytes(photo);
                    person.feature = feaStr;
                    dbManager.addPerson(person);
                }
                else
                {
                    Toast.makeText(AddActivity.this, "提取人脸特征码失败", Toast.LENGTH_SHORT).show();
                }

                // 跳转
                Intent intent = new Intent(AddActivity.this, ManageActivity.class);
                startActivity(intent);
                finish();
                break;
            default:
                break;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case PHOTO_REQUEST_TAKEPHOTO:
                if (tempFile == null) return;
                Uri imageUri = null;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    //添加这一句表示对目标应用临时授权该Uri所代表的文件
                    //通过FileProvider创建一个content类型的Uri
                    imageUri = FileProvider.getUriForFile(AddActivity.this, BuildConfig.APPLICATION_ID + ".fileprovider", tempFile);
//            outputUri = Uri.fromFile(new File(crop_image));
                    //TODO:outputUri不需要ContentUri,否则失败
                    //outputUri = FileProvider.getUriForFile(activity, "com.solux.furniture.fileprovider", new File(crop_image));
                } else {
                    imageUri = Uri.fromFile(tempFile);
//            outputUri = Uri.fromFile(new File(crop_image));
                }
                startPhotoZoom(imageUri, 150);
                break;
            case PHOTO_REQUEST_GALLERY:
                if (data != null)
                    startPhotoZoom(data.getData(), 150);
                break;
            case PHOTO_REQUEST_CUT:
                if (data != null)
                    try {
                        setPicToView(data);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 解决小米手机上获取图片路径为null的情况
     */
    public Uri getPictureUri(android.content.Intent intent) {
        Uri uri = intent.getData();
        String type = intent.getType();
        if (uri.getScheme().equals("file") && (type.contains("image/"))) {
            String path = uri.getEncodedPath();
            if (path != null) {
                path = Uri.decode(path);
                ContentResolver cr = getContentResolver();
                StringBuffer buff = new StringBuffer();
                buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=")
                        .append("'" + path + "'").append(")");
                Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        new String[]{MediaStore.Images.ImageColumns._ID},
                        buff.toString(), null, null);
                int index = 0;
                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
                    index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
                    // set _id value
                    index = cur.getInt(index);
                }
                if (index == 0) {
                    // do nothing
                } else {
                    Uri uri_temp = Uri
                            .parse("content://media/external/images/media/"
                                    + index);
                    if (uri_temp != null) {
                        uri = uri_temp;
                    }
                }
            }
        }
        return uri;
    }


    /**
     * 裁剪图片
     */
    private void startPhotoZoom(Uri uri, int size) {

        File CropPhoto = new File(getExternalCacheDir(), "Crop.jpg");//这个是创建一个截取后的图片路径和名称。
        try {
            if (CropPhoto.exists()) {
                CropPhoto.delete();
            }
            CropPhoto.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        uritempFile = Uri.fromFile(CropPhoto);
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
        }
        intent.putExtra("crop", "true");
        intent.putExtra("scale", true);

        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        //输出的宽高

        intent.putExtra("outputX", size);
        intent.putExtra("outputY", size);

        intent.putExtra("return-data", false);
        uritempFile = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "small.jpg");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);


//        Intent intent = new Intent("com.android.camera.action.CROP");
//        intent.setDataAndType(uri, "image/*");
//        // crop为true是设置在开启的intent中设置显示的view可以剪裁
//        intent.putExtra("crop", "true");
//
//        // aspectX aspectY 是宽高的比例
//        intent.putExtra("aspectX", 1);
//        intent.putExtra("aspectY", 1);
//
//        // outputX,outputY 是剪裁图片的宽高
//        intent.putExtra("outputX", size);
//        intent.putExtra("outputY", size);
//
//        /**
//         * 此方法返回的图片只能是小图片（sumsang测试为高宽160px的图片）
//         * 故只保存图片Uri，调用时将Uri转换为Bitmap，此方法还可解决miui系统不能return data的问题
//         */
//        //intent.putExtra("return-data", true);
//
//        //裁剪后的图片Uri路径，uritempFile为Uri类变量
//        Uri uritempFile = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "small.jpg");
//        intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);
//        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());

        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }


//    private void startPhotoZoom(Uri uri, int size) {
//        Intent intent = new Intent("com.android.camera.action.CROP");
//        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//        intent.setDataAndType(uri, "image/*");
//        // crop为true是设置在开启的intent中设置显示的view可以剪裁
//        intent.putExtra("crop", "false");
//        // aspectX aspectY 是宽高的比例
//        intent.putExtra("aspectX", 1);
//        intent.putExtra("aspectY", 1);
//        // outputX,outputY 是剪裁图片的宽高
//        intent.putExtra("outputX", size);
//        intent.putExtra("outputY", size);
//        intent.putExtra("return-data", true);
//        startActivityForResult(intent, PHOTO_REQUEST_CUT);
//    }

    // 将进行剪裁后的图片显示到UI界面上
    @SuppressWarnings("deprecation")
    private void setPicToView(Intent picdata) throws FileNotFoundException {

//        Uri url=getPictureUri(picdata);
        if (uritempFile!=null)
        {
            Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uritempFile));
            if (bitmap!=null)
            {
                photo = bitmap;
                // 更新UI
                Drawable drawable = new BitmapDrawable(photo);
                leftImageView.setBackgroundDrawable(drawable);
            }
        }



//        Bundle bundle = picdata.getExtras();
//        if (bundle != null) {
//            photo = bundle.getParcelable("data");
//            // 更新UI
//            Drawable drawable = new BitmapDrawable(photo);
//            leftImageView.setBackgroundDrawable(drawable);
//        }
    }

    private void saveBitmap(Bitmap bmp, String name) {
        File file = new File("/sdcard/wis/images/manage");
        if (!file.exists()) {
            file.mkdirs();
        }
        file = new File("/sdcard/wis/images/manage/" + name + ".jpg");
        try {
            file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 90, fos);
            fos.flush();
            fos.close();
            new SingleMediaScanner(this, file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        onDestroy();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dbManager.closeDB();
    }

    @Override
    public void onResume() {
        super.onResume();
//        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
//        MobclickAgent.onPause(this);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
            default:
                break;
        }
        return true;
    }

    private static Uri getUriForFile(Context context, File file) {
        if (context == null || file == null) {
            throw new NullPointerException();
        }
        Uri uri;
        if (Build.VERSION.SDK_INT >= 24) {
            uri = FileProvider.getUriForFile(context.getApplicationContext(), BuildConfig.APPLICATION_ID + ".provider", file);
        } else {
            uri = Uri.fromFile(file);
        }
        return uri;
    }
}
